package gavdi.dk.util;


import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;


import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import Exceptions.ConverterException;
import Exceptions.HttpNodeClientException;

public class HttpNodeClient {
	private static HttpPost httpPost;
	private static HttpClient client;
	private static String URL;
	private static String err_connectionTimeout = "Connection timeout\n Couldn't connect to the server";
	private static String err_serverConnection = "Please check your internet connection and try again";
	

	public HttpNodeClient(){
		
	}
	
	public HttpNodeClient connect(){
		return (HttpNodeClient) client;
		
	}
	
	
		
	public HttpClient getClient() {
		return client;
	}

	public static void startConnection(){
		URL = "http://172.22.13.159:8000/"; // Make a method that gets URL from a property/XML/document file
		httpPost = new HttpPost(URL);
		
		System.out.println("Connecting to: " + URL);
		
		HttpParams httpParameters = new BasicHttpParams(); 
		int timeoutConnection = 3000; 
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
		int timeoutSocket = 3000; 
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
		client = new DefaultHttpClient(httpParameters);

		

	}
	public void killConnection(){
		client.getConnectionManager().shutdown();
		System.out.println("KILLLLLLLLLLLLLLLLLLLLLLLL");
	}

	
	public static void sendJSON(JSONObject jsonObj) throws HttpNodeClientException {
		HttpResponse response = createPOST(jsonObj);
		createResponse(response);
	}
	

	
	private static HttpResponse createPOST(JSONObject jsonObj) throws HttpNodeClientException {
		
		StringEntity entity;
		
		try {
			
			entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
			entity.setContentType("application/json");

			httpPost.setEntity(entity);

			return client.execute(httpPost);
			
		} catch (ConnectTimeoutException e) {
		
			e.printStackTrace();
			throw new HttpNodeClientException("HttpNodeClientException/ConnectTimeoutException - createPOST():" + e.getMessage(), err_connectionTimeout);
		
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new HttpNodeClientException("HttpNodeClientException/UnsupportedEncodingException - createPOST():" + e.getMessage(), "");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new HttpNodeClientException("HttpNodeClientException/ClientProtocolException - createPOST():" + e.getMessage(), "");
		} catch (IOException e) {

			e.printStackTrace();
			throw new HttpNodeClientException("HttpNodeClientException/IOException - createPOST():" + e.getMessage(), err_serverConnection);
		} catch (Exception e)	{
			e.printStackTrace();
			throw new HttpNodeClientException("HttpNodeClientException/Exception - createPOST():" + e.getMessage(),"");
		}
	}

	private static  void createResponse(HttpResponse response) throws HttpNodeClientException {
		JSONObject jsonObj = null;
		// Henter response data fra server vha. httpResponse
		HttpEntity entity1 = response.getEntity();
		if (entity1 != null) {
			InputStream is = null;
			try {
				is = entity1.getContent();
				// convert stream to string
				String result = Tools.convertStreamToString(is);
				
				//Remove []
				//if(result.startsWith("["))
				//	result = result.substring(1, result.length()-1);
				// Create JSON Object
				jsonObj = (JSONObject) new JSONTokener(result).nextValue();
				int status = jsonObj.getInt("status");
				
				switch (status) {
				case 1: throw new HttpNodeClientException(" ", "User not found Error #1");
				case 2: throw new HttpNodeClientException(" ", err_connectionTimeout + "\n" + "Error#2");
				}

	        
				
				
			} catch (IllegalStateException e) {
				e.printStackTrace();
				throw new HttpNodeClientException("HttpNodeClientException/IllegalStateException - createResponse():" + e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				throw new HttpNodeClientException("HttpNodeClientException/IOException - createResponse():" + e.getMessage());
			} catch (JSONException e) {
				e.printStackTrace();
				throw new HttpNodeClientException("HttpNodeClientException/JSONException - createResponse():" + e.getMessage());
			} catch (ConverterException e){
				e.printStackTrace();
				throw new HttpNodeClientException("HttpNodeClientException/ConverterException - createResponse():" + e.getMessage());
			}
		}
		

	}



	}
	
	




	


